package com.rainszj.config;

import com.rainszj.pojo.po.User;
import com.rainszj.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 自定义的 Realm，需要继承 AuthorizingRealm
 * 相当于是安全实体(DataSource)，获取用户、角色、权限
 *
 * @author rainszj
 * 2020/3/10
 */
public class UserRealm extends AuthorizingRealm {
    private final static Logger logger = LoggerFactory.getLogger(UserRealm.class);

    @Autowired
    UserService userService;

    // 授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // System.out.println("执行了=>授权doGetAuthorizationInfo");


        return null;
    }

    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //  System.out.println("执行了=>认证doGetAuthorizationInfo");

        // 这里的Token，是全局的，你在 login方法中设置了，这里可以获取到
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        User loginUser = userService.queryUserByName(userToken.getUsername());

        // 没有这个人
        if (loginUser == null) {
            // UnknownAccountException
            return null;
        }

        // 盐值
        ByteSource credentialsSalt = ByteSource.Util.bytes(userToken.getUsername());
        // 登录成功设置当前用户的登录信息
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        session.setAttribute("loginUser", loginUser);

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(loginUser, loginUser.getPassword(), credentialsSalt, getName());

        return info;
    }
}